<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends BaseController
{
    /**
     * 获取分类
     * @return \Illuminate\Http\JsonResponse
     */
   public function getCateGory()
   {

       return $this->success($this->getTree(Category::with(['products'])->get()->toArray()));
   }

    protected function getTree(array $data)
    {
        $items = [];
        foreach ($data as $v){
            $items[$v['id']] = $v; // $items[1] =
        }
        $tree = array(); //格式化好的树
        foreach ($items as $item)
            if (isset($items[$item['pid']]))
                $items[$item['pid']]['chlid'][] = &$items[$item['id']];
            else
                $tree[] = &$items[$item['id']];
        return $tree;
    }
}
